package com.chainyoung.component_tmperson.ui.activity.hdwallet;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.entity.HdWalletTokenCache;
import com.chainyoung.common.appcommon.entity.HdWalletTokenTransaction;
import com.chainyoung.common.appcommon.hdwallet.TokenBalance;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.common_widget.loadsir.callback.Callback;
import com.chainyoung.common.common_widget.loadsir.core.LoadService;
import com.chainyoung.common.common_widget.loadsir.core.LoadSir;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.custom_widget.EmptyCallback;
import com.chainyoung.common.custom_widget.LoadingCallback;
import com.chainyoung.common.custom_widget.RetryCallback;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.ui.adapter.HdWalletTokenTransactionAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.HdWalletTokenTransactionContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.HdWalletTokenTransactionPresenter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.appcommon.hdwallet.ExchangeCalculator.ONE_ETHER;

public class HdWalletTokenActivity extends BaseActivity<HdWalletTokenTransactionPresenter> implements HdWalletTokenTransactionContract.View {

    @BindView(R2.id.tv_balance)
    TextView tvBalance;
    @BindView(R2.id.tv_turn_in)
    TextView tvTurnIn;
    @BindView(R2.id.tv_turn_out)
    TextView tvTurnOut;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    private HdWalletCache hdWallet;
    private HdWalletTokenCache hdWalletTokenCache;
    private HdWalletTokenTransactionAdapter adapter;
    private List<HdWalletTokenTransaction> mData = new ArrayList<>();

    private int pageNo = 1;
    private boolean isCanloadMore;

    private LoadService loadService;


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        hdWallet = (HdWalletCache) getIntent().getSerializableExtra("hdWallet");
        hdWalletTokenCache = (HdWalletTokenCache) getIntent().getSerializableExtra("hdWalletTokenCache");
        setCurrentTitle(hdWalletTokenCache.getTokenSymbol());
        tvBalance.setText(hdWalletTokenCache.getBalance());

        initRecyclerView();
        initLoadSir();

    }

    private void initRecyclerView() {
        adapter = new HdWalletTokenTransactionAdapter(mData, hdWallet.getAddress());
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        rvList.addItemDecoration(itemDecoration);
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        rvList.setAdapter(adapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    getTransactionList();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                getTransactionList();
            }
        });
    }

    private void initLoadSir() {
        LoadSir loadSir = new LoadSir.Builder()
                .addCallback(new LoadingCallback())
                .addCallback(new EmptyCallback())
                .addCallback(new RetryCallback())
                .setDefaultCallback(LoadingCallback.class)
                .build();
        loadService = loadSir.register(refreshLayout, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                pageNo = 1;
                getTransactionList();
            }
        });

    }

    @Override
    protected void initData() {
        pageNo = 1;
        getTransactionList();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_hdwallet_token;
    }

    @OnClick(R2.id.tv_turn_out)
    void turnOut() {
        Intent intent = new Intent(mContext, HdWalletSendTranscationActivity.class);
        intent.putExtra("hdWallet", hdWallet);
        intent.putExtra("hdWalletTokenCache", hdWalletTokenCache);
        mContext.startActivity(intent);

    }

    @OnClick(R2.id.tv_turn_in)
    void turnIn() {
        Intent intent = new Intent(mContext, HdWalletCodeActivity.class);
        intent.putExtra("hdWallet", hdWallet);
        intent.putExtra("hdWalletToken",hdWalletTokenCache);
        startActivity(intent);
    }

    private void getTransactionList() {
        mPresenter.getSingleTokenTransfers(hdWalletTokenCache.getContractAddress(), hdWallet.getAddress(), pageNo, LibConstant.PAGE_SIZ);
    }


    @Override
    public void onGetSingleTokenTransfersSuccessed(String data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        List<HdWalletTokenTransaction> datas = new Gson().fromJson(data, new TypeToken<List<HdWalletTokenTransaction>>() {
        }.getType());
        if (pageNo == 1) {
            mData.clear();
        }
        if (datas != null) {
            mData.addAll(datas);
            if (datas.size() < LibConstant.PAGE_SIZ) {
                isCanloadMore = false;
                refreshLayout.setEnableLoadMore(false);
            } else {
                isCanloadMore = true;
                refreshLayout.setEnableLoadMore(true);
            }
        }
        adapter.notifyDataSetChanged();
        if (mData.isEmpty()) {
            loadService.showCallback(EmptyCallback.class);
        } else {
            loadService.showSuccess();
        }

    }

    @Override
    public void onGetSingleTokenTrasferFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        loadService.showCallback(RetryCallback.class);
    }

    @Override
    public void onGetTokenBalanceSuccessed(TokenBalance data) {
        tvBalance.setText(new BigDecimal(data.getBalance()).divide(ONE_ETHER).setScale(4, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
    }

    @Override
    public void onGetTokenBalanceFailed(String contractAddr) {

    }


    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getTokenBalance(hdWalletTokenCache.getContractAddress(), hdWalletTokenCache.getAddress());
    }
}
